//
//  FoodListDetailViewController.m
//  shise
//
//  Created by 毛志鹏 on 14/12/17.
//  Copyright (c) 2014年 MZP. All rights reserved.
//

#import "FoodListDetailViewController.h"
#import "NetHandler.h"
#import "Food.h"
#import "MoreDetailCell.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "XHYScrollingNavBarViewController.h"
#import "UserDetailViewController.h"
#import "DataBaseHaneler.h"
#import "DetailViewController.h"

@interface FoodListDetailViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) NSString *refresh; //tableView刷新的接口

@property (nonatomic, retain) NSString *userHead_url; // 食色官方信息
@property (nonatomic, retain) NSString *userTitle;
@property (nonatomic, retain) NSString *userDesc;

@property (nonatomic, retain) NSString *picTitle;  // 食单发起者的信息
@property (nonatomic, retain) NSString *picDesc;

@property (nonatomic, retain) NSMutableArray *foodArr;  // 美食数组

@property (nonatomic, retain) UITableView *tableView;  //



@end

@implementation FoodListDetailViewController

- (void)dealloc
{
    [_address release];
    [_refresh release];
    [_userHead_url release];
    [_userTitle release];
    [_userDesc release];
    [_picTitle release];
    [_picDesc release];
    [_foodArr release];
    [_tableView release];
    [super dealloc];
}
// 处理数据的方法
- (void)handleData
{
//    NSLog(@"%@", self.address);
//    NSString *str = [NSString stringWithFormat:@"https://api.shiseapp.com%@/?", self.address];
    
    NSString *str = [NSString stringWithFormat:@"https://api.shiseapp.com%@", self.address];
//    NSString *str = @"https://api.shiseapp.com/v2/slist/l_CLa9.UOqHZ/?";
    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        NSError *resultError = nil;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&resultError];
        
        NSArray *arr = [result objectForKey:@"data"];
        
        self.refresh = [[result objectForKey:@"pagination"] objectForKey:@"nextUrl"];
        
        // 对数据源初始化
        self.foodArr = [NSMutableArray array];
        
        for (NSDictionary *tempDic in arr) {
            if ([[tempDic objectForKey:@"type"] isEqualToString:@"UserCard"]) {  // 食色官方卡片
                
                self.userTitle = [tempDic objectForKey:@"title"];
                self.userDesc = [tempDic objectForKey:@"desc"];
                self.userHead_url = [[tempDic objectForKey:@"user"] objectForKey:@"avatar"];
                
            } else if ([[tempDic objectForKey:@"type"] isEqualToString:@"PicCard"]) {  // 发起者卡片
                
                self.picTitle = [tempDic objectForKey:@"title"];
                self.picDesc = [tempDic objectForKey:@"desc"];
                
            } else if ([[tempDic objectForKey:@"type"] isEqualToString:@"MediaCard"]) {  // 美食卡片
                
                Food *food = [[Food alloc] initWithDictionary:tempDic];
                [self.foodArr addObject:food];
                [food release];
                
            }
        }
        
        // 重新加载数据
        [self.tableView reloadData];
    }];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor cyanColor];
    
    self.tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    [self.view addSubview: self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    // 去掉表格分割线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView release];
    
    self.tableView.showsVerticalScrollIndicator = NO;
    
    self.title = @"食单详情";
    
    [self handleData];
    
    [self setupRefresh];
    
//    [self followRollingScrollView:self.tableView];

    
    // Do any additional setup after loading the view.
}

// tableView两个代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.foodArr.count + 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        UITableViewCell *user = [tableView dequeueReusableCellWithIdentifier:@"officail"];
        if (user == nil) {
            user = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"officail"]autorelease];
        }
        
        UIImageView *myImageView = [[UIImageView alloc] initWithFrame:user.imageView.bounds];
        myImageView.image = [UIImage imageNamed:@"iconfont-circle-block.png"];
//        user.imageView.layer.cornerRadius = 15;
        [user.imageView setImageWithURL:[NSURL URLWithString:self.userHead_url]];
        
        [user.imageView addSubview:myImageView];
        
        user.textLabel.text = self.userTitle;
        user.detailTextLabel.text = self.userDesc;
        [myImageView release];
        return user;
    } else if (indexPath.row == 1) {
        UITableViewCell *pic = [tableView dequeueReusableCellWithIdentifier:@"PicCard"];
        if (pic == nil) {
            pic = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"PicCard"]autorelease];
        }
        pic.textLabel.text = self.picTitle;
        pic.detailTextLabel.text = self.picDesc;
        return pic;
    } else {
        MoreDetailCell *foodCell = [tableView dequeueReusableCellWithIdentifier:@"food"];
        if (foodCell == nil) {
            foodCell = [[[MoreDetailCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"food"]autorelease];
        }
        
        // 为cell上的按钮添加点击跳转详情的方法
        
        foodCell.foodImageViewButton.tag = 10000 + indexPath.row;
        [foodCell.foodImageViewButton addTarget:self action:@selector(clickPic:) forControlEvents:UIControlEventTouchUpInside];
        
        foodCell.userHeadImageViewButton.tag = 20000 + indexPath.row;
        [foodCell.userHeadImageViewButton addTarget:self action:@selector(clickHead:) forControlEvents:UIControlEventTouchUpInside];
        
        foodCell.praiseImageViewButton.tag = 30000 + indexPath.row;
        [foodCell.praiseImageViewButton addTarget:self action:@selector(clickPraise:) forControlEvents:UIControlEventTouchUpInside];
        
        foodCell.markImagViewButton.tag = 40000 + indexPath.row;
        [foodCell.markImagViewButton addTarget:self action:@selector(clickMark:) forControlEvents:UIControlEventTouchUpInside];
        
        Food *food = [self.foodArr objectAtIndex:indexPath.row - 2];
        foodCell.food = food;
        
        if (food.clickPraiseCount % 2 == 0) {
            
            foodCell.praiseImageView.image = [UIImage imageNamed:@"praiseFont.png"];
        } else {
            
            foodCell.praiseImageView.image = [UIImage imageNamed:@"praiseBehind.png"];
        }
        if (food.clickMarkCount != 0) {
            
            foodCell.markImageView.image = [UIImage imageNamed:@"markBehind.png"];
        } else {
            
            foodCell.markImageView.image = [UIImage imageNamed:@"mark.png"];
        }
        
        return foodCell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 35;
    } else if (indexPath.row == 1) {
        return 60;
    } else {
        return 430;
    }
}

- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    //warning 自动刷新(一进入程序就下拉刷新)
    [self.tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = @"下拉可以刷新";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新";
    self.tableView.headerRefreshingText = @"正在刷新...";
    
    self.tableView.footerPullToRefreshText = @"上拉可以加载更多数据";
    self.tableView.footerReleaseToRefreshText = @"松开马上加载更多数据";
    self.tableView.footerRefreshingText = @"正在刷新...";
    
}
// 下拉刷新
- (void)headerRereshing
{
    [self handleData];
    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView headerEndRefreshing];
    });
}
// 上啦加载
- (void)footerRereshing
{
    NSString *str = self.refresh;
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        NSError *resultError = nil;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&resultError];
        
        NSArray *arr = [result objectForKey:@"data"];
        self.refresh = [[result objectForKey:@"pagination"] objectForKey:@"nextUrl"];
        
        // 新建一个数组用来存放上拉刷新后 请求的美食对象
        NSMutableArray *newFoodArr = [NSMutableArray array];
        for (NSDictionary *dic in arr) {
            Food *food = [[Food alloc] initWithDictionary:dic];
            [newFoodArr addObject:food];
            [food release];
        }
        [self.foodArr addObjectsFromArray:newFoodArr];
        
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            [self.tableView reloadData];
            
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [self.tableView footerEndRefreshing];
        });
        
    }];
    
}


// 点击图片跳转详情
- (void) clickPic:(UIButton *)foodPic
{
    
//    [self showNavi];
    
    DetailViewController *foodDetail = [[DetailViewController alloc] init];
    
    foodDetail.detailApi = [[self.foodArr objectAtIndex:foodPic.tag - 10000 - 2] objId];
    
    foodDetail.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:foodDetail animated:YES];
    [foodDetail release];
}
// 点击头像跳转用户详情
- (void) clickHead:(UIButton *)userHead
{
//    [self showNavi];
    
    UserDetailViewController *userDetail = [[UserDetailViewController alloc] init];
    
    Food *temp = [self.foodArr objectAtIndex:userHead.tag - 20000 - 2];
    
    userDetail.userApi = [temp.user objectForKey:@"id"];
    
    userDetail.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:userDetail animated:YES];
    [userDetail release];
}
// 点击“赞”的时候执行的方法
- (void)clickPraise:(UIButton *)button
{
    
    // 当点击赞的时候赞的图片变成红色的同时赞的人数加1
    NSInteger numberOfCell = button.tag - 30000 - 2;
    Food *food = [self.foodArr objectAtIndex:numberOfCell];
    if (food.clickPraiseCount % 2 == 0) {
        
        food.clickPraiseCount += 1;
        
        NSString *likeCount = food.likeCount;
        NSInteger likeCountNew = [likeCount integerValue];
        likeCountNew = likeCountNew + 1;
        //    NSNumber *num = [likeCount description];
        food.likeCount = [NSString stringWithFormat:@"%ld", (long)likeCountNew];
        //        self.number = 1;
        [self.tableView reloadData];
        
    } else {
        
        food.clickPraiseCount += 1;
        
        NSString *likeCount = food.likeCount;
        NSInteger likeCountNew = [likeCount integerValue];
        likeCountNew = likeCountNew - 1;
        //    NSNumber *num = [likeCount description];
        food.likeCount = [NSString stringWithFormat:@"%ld", (long)likeCountNew];
        //        self.number = 1;
        [self.tableView reloadData];
    }
}

// 点击“马克”的时候执行的方法
- (void)clickMark:(UIButton *)button
{
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    if ([def objectForKey:@"userName"] == nil) {
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
    } else {
        
        NSInteger numberOfCell = button.tag - 40000 - 2;
        Food *food = [self.foodArr objectAtIndex:numberOfCell];
        food.clickMarkCount += 1;
        [self.tableView reloadData];
        // 当收藏本条美食信息的时候就讲本条没事信息存储到本地 当点击我的收藏的时候从本地读取信息 并显示
        DataBaseHaneler *handler = [DataBaseHaneler shareInstance];
        // 打开数据库
        [handler openDB];
        // 创建美食表表
        [handler createFoodTable];
        // 添加一条美食数据
        [handler insertFood:food userName:[def objectForKey:@"userName"]];
        
    }
    
    
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
